﻿using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.MenuCommand;
using RBAC_Uthorization.Read.API.DTO;
using RBAC_Uthorization.Read.API.DTO.Response.Menu;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.MenuHandler
{
    public class MenuOperationPidCommandHandlers : IRequestHandler<MenuOperationPidCommand, ApiResult<List<MenuOperationPidDto>>>
    {
        private readonly IMenuRepository _menuRepository;
        private readonly ILogger<MenuOperationPidCommandHandlers> _logger;

        public MenuOperationPidCommandHandlers(IMenuRepository menuRepository, ILogger<MenuOperationPidCommandHandlers> logger)
        {
            _menuRepository = menuRepository;
            _logger = logger;
        }

        public async Task<ApiResult<List<MenuOperationPidDto>>> Handle(MenuOperationPidCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var menu = await _menuRepository.GetAllAsunc(x => x.parent_id == request.Pid&&x.sys_id==request.sys_id&&x.del_flag==0);
                if (menu == null)
                {
                    return new ApiResult<List<MenuOperationPidDto>> { Code = ResultCode.NoContent, Message = "菜单不存在" };
                }
                var menuOperationPidDto = menu.Select(x => new MenuOperationPidDto
                {
                    menu_url = x.menu_url,
                    perms = x.perms,
                }).ToList();
                return new ApiResult<List<MenuOperationPidDto>> { Data = menuOperationPidDto };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取菜单操作失败");
                return new ApiResult<List<MenuOperationPidDto>> { Code = ResultCode.Fail, Message = "获取菜单操作失败" };
            }
         
        }
    }
}
